// 忘记密码页面组件

import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Box,
  Card,
  TextField,
  Button,
  Typography,
  Alert,
  CircularProgress,
  IconButton,
  InputAdornment,
} from '@mui/material';
import {
  ArrowBack,
  Email,
  Lock,
  Send,
  CheckCircle,
  Visibility,
  VisibilityOff,
} from '@mui/icons-material';
import { useAuth } from '../../hooks';
import { ResetPasswordRequest, VerificationPurpose } from '../../types';
import styles from './ForgotPassword.module.css';

type Step = 'email' | 'reset' | 'success';

const ForgotPassword: React.FC = () => {
  const navigate = useNavigate();
  const [currentStep, setCurrentStep] = useState<Step>('email');
  const [formData, setFormData] = useState({
    email: '',
    verificationCode: '',
    newPassword: '',
    confirmPassword: '',
  });
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [errors, setErrors] = useState<{[key: string]: string}>({});
  const [verificationSent, setVerificationSent] = useState(false);
  const [countdown, setCountdown] = useState(0);

  const { sendVerificationCode, resetPassword, loading, error } = useAuth();

  // 倒计时效果
  useEffect(() => {
    let timer: NodeJS.Timeout;
    if (countdown > 0) {
      timer = setTimeout(() => setCountdown(countdown - 1), 1000);
    }
    return () => clearTimeout(timer);
  }, [countdown]);

  // 验证邮箱步骤
  const validateEmailStep = (): boolean => {
    const newErrors: {[key: string]: string} = {};

    if (!formData.email.trim()) {
      newErrors.email = '请输入邮箱地址';
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = '请输入有效的邮箱地址';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 验证重置密码步骤
  const validateResetStep = (): boolean => {
    const newErrors: {[key: string]: string} = {};

    if (!formData.verificationCode.trim()) {
      newErrors.verificationCode = '请输入验证码';
    } else if (!/^\d{6}$/.test(formData.verificationCode)) {
      newErrors.verificationCode = '验证码应为6位数字';
    }

    if (!formData.newPassword) {
      newErrors.newPassword = '请输入新密码';
    } else if (formData.newPassword.length < 6 || formData.newPassword.length > 20) {
      newErrors.newPassword = '密码长度应在6-20字符之间';
    }

    if (!formData.confirmPassword) {
      newErrors.confirmPassword = '请确认新密码';
    } else if (formData.newPassword !== formData.confirmPassword) {
      newErrors.confirmPassword = '两次输入的密码不一致';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 处理输入变化
  const handleInputChange = (field: string) => (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    setFormData(prev => ({
      ...prev,
      [field]: event.target.value
    }));
    
    // 清除对应字段的错误
    if (errors[field]) {
      setErrors(prev => ({
        ...prev,
        [field]: ''
      }));
    }
  };

  // 发送验证码
  const handleSendVerificationCode = async () => {
    if (!validateEmailStep()) {
      return;
    }

    try {
      await sendVerificationCode({
        email: formData.email,
        purpose: VerificationPurpose.PASSWORD_RESET
      });
      setVerificationSent(true);
      setCountdown(60);
      setCurrentStep('reset');
    } catch (err) {
      console.error('发送验证码失败:', err);
    }
  };

  // 重置密码
  const handleResetPassword = async (event: React.FormEvent) => {
    event.preventDefault();
    
    if (!validateResetStep()) {
      return;
    }

    const requestData: ResetPasswordRequest = {
      email: formData.email,
      verificationCode: formData.verificationCode,
      newPassword: formData.newPassword,
    };

    try {
      await resetPassword(requestData);
      setCurrentStep('success');
    } catch (err) {
      console.error('重置密码失败:', err);
    }
  };

  // 重新发送验证码
  const handleResendCode = async () => {
    try {
      await sendVerificationCode({
        email: formData.email,
        purpose: VerificationPurpose.PASSWORD_RESET
      });
      setCountdown(60);
    } catch (err) {
      console.error('重新发送验证码失败:', err);
    }
  };

  // 切换密码显示
  const handleTogglePasswordVisibility = () => {
    setShowPassword(prev => !prev);
  };

  const handleToggleConfirmPasswordVisibility = () => {
    setShowConfirmPassword(prev => !prev);
  };

  // 返回登录页面
  const handleBackToLogin = () => {
    navigate('/auth/login');
  };

  // 返回上一步
  const handleBackToEmail = () => {
    setCurrentStep('email');
    setErrors({});
  };

  // 渲染步骤指示器
  const renderStepIndicator = () => (
    <div className={styles.stepIndicator}>
      <div className={`${styles.step} ${currentStep === 'email' ? styles.active : (currentStep === 'reset' || currentStep === 'success') ? styles.completed : ''}`}>
        <div className={styles.stepNumber}>1</div>
        <span>验证邮箱</span>
      </div>
      <div className={styles.stepConnector}></div>
      <div className={`${styles.step} ${currentStep === 'reset' ? styles.active : currentStep === 'success' ? styles.completed : ''}`}>
        <div className={styles.stepNumber}>2</div>
        <span>重置密码</span>
      </div>
      <div className={styles.stepConnector}></div>
      <div className={`${styles.step} ${currentStep === 'success' ? styles.active : ''}`}>
        <div className={styles.stepNumber}>3</div>
        <span>完成</span>
      </div>
    </div>
  );

  // 渲染邮箱验证步骤
  const renderEmailStep = () => (
    <>
      <div className={styles.header}>
        <Typography variant="h4" className={styles.title}>
          忘记密码
        </Typography>
        <Typography variant="body2" className={styles.subtitle}>
          输入您的邮箱地址，我们将发送验证码用于重置密码
        </Typography>
      </div>

      <form onSubmit={(e) => { e.preventDefault(); handleSendVerificationCode(); }} className={styles.form}>
        <TextField
          fullWidth
          label="邮箱地址"
          type="email"
          variant="outlined"
          value={formData.email}
          onChange={handleInputChange('email')}
          error={!!errors.email}
          helperText={errors.email}
          className={styles.inputField}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <Email color="action" />
              </InputAdornment>
            ),
          }}
        />

        <div className={styles.loadingWrapper}>
          <Button
            type="submit"
            fullWidth
            variant="contained"
            className={styles.resetButton}
            disabled={loading}
            startIcon={<Send />}
          >
            {loading ? '发送中...' : '发送验证码'}
          </Button>
          {loading && (
            <CircularProgress size={24} className={styles.loading} />
          )}
        </div>

        {error && (
          <Alert severity="error" className={styles.errorMessage}>
            {error}
          </Alert>
        )}
      </form>
    </>
  );

  // 渲染重置密码步骤
  const renderResetStep = () => (
    <>
      <div className={styles.header}>
        <Typography variant="h4" className={styles.title}>
          重置密码
        </Typography>
        <Typography variant="body2" className={styles.subtitle}>
          请输入发送到 {formData.email} 的验证码，并设置新密码
        </Typography>
      </div>

      <form onSubmit={handleResetPassword} className={styles.form}>
        <div className={styles.verificationSection}>
          <TextField
            label="验证码"
            variant="outlined"
            value={formData.verificationCode}
            onChange={handleInputChange('verificationCode')}
            error={!!errors.verificationCode}
            helperText={errors.verificationCode}
            className={styles.verificationInput}
            placeholder="请输入6位数字验证码"
          />
          <Button
            variant="outlined"
            onClick={handleResendCode}
            disabled={countdown > 0 || loading}
            className={styles.verificationButton}
            startIcon={<Send />}
          >
            {countdown > 0 ? `${countdown}s` : '重新发送'}
          </Button>
        </div>

        <TextField
          fullWidth
          label="新密码"
          type={showPassword ? 'text' : 'password'}
          variant="outlined"
          value={formData.newPassword}
          onChange={handleInputChange('newPassword')}
          error={!!errors.newPassword}
          helperText={errors.newPassword}
          className={styles.inputField}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <Lock color="action" />
              </InputAdornment>
            ),
            endAdornment: (
              <InputAdornment position="end">
                <IconButton
                  onClick={handleTogglePasswordVisibility}
                  edge="end"
                >
                  {showPassword ? <VisibilityOff /> : <Visibility />}
                </IconButton>
              </InputAdornment>
            ),
          }}
        />

        <TextField
          fullWidth
          label="确认新密码"
          type={showConfirmPassword ? 'text' : 'password'}
          variant="outlined"
          value={formData.confirmPassword}
          onChange={handleInputChange('confirmPassword')}
          error={!!errors.confirmPassword}
          helperText={errors.confirmPassword}
          className={styles.inputField}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <Lock color="action" />
              </InputAdornment>
            ),
            endAdornment: (
              <InputAdornment position="end">
                <IconButton
                  onClick={handleToggleConfirmPasswordVisibility}
                  edge="end"
                >
                  {showConfirmPassword ? <VisibilityOff /> : <Visibility />}
                </IconButton>
              </InputAdornment>
            ),
          }}
        />

        <div className={styles.loadingWrapper}>
          <Button
            type="submit"
            fullWidth
            variant="contained"
            className={styles.resetButton}
            disabled={loading}
          >
            {loading ? '重置中...' : '重置密码'}
          </Button>
          {loading && (
            <CircularProgress size={24} className={styles.loading} />
          )}
        </div>

        {error && (
          <Alert severity="error" className={styles.errorMessage}>
            {error}
          </Alert>
        )}

        <Button
          variant="text"
          onClick={handleBackToEmail}
          startIcon={<ArrowBack />}
          style={{ marginTop: '16px' }}
        >
          返回上一步
        </Button>
      </form>
    </>
  );

  // 渲染成功步骤
  const renderSuccessStep = () => (
    <div className={styles.successCard}>
      <CheckCircle className={styles.successIcon} />
      <Typography variant="h5" className={styles.successTitle}>
        密码重置成功
      </Typography>
      <Typography variant="body2" className={styles.successDesc}>
        您的密码已成功重置，现在可以使用新密码登录您的账户
      </Typography>
      <Button
        fullWidth
        variant="contained"
        onClick={handleBackToLogin}
        className={styles.resetButton}
      >
        立即登录
      </Button>
    </div>
  );

  return (
    <Box className={styles.container}>
      <Card className={styles.forgotPasswordCard}>
        {currentStep !== 'success' && renderStepIndicator()}
        
        {currentStep === 'email' && renderEmailStep()}
        {currentStep === 'reset' && renderResetStep()}
        {currentStep === 'success' && renderSuccessStep()}

        {currentStep === 'email' && (
          <div className={styles.backToLogin}>
            <a 
              href="#" 
              onClick={handleBackToLogin}
              className={styles.backToLoginLink}
            >
              <ArrowBack fontSize="small" />
              返回登录
            </a>
          </div>
        )}
      </Card>
    </Box>
  );
};

export default ForgotPassword; 